import { ParseIntPipe, Query, Sse, MessageEvent, HttpException, HttpStatus } from '@nestjs/common';
import { Body, Controller, DefaultValuePipe, Get, Post } from '@nestjs/common';
import { Observable, interval } from 'rxjs';
import { map } from 'rxjs/operators';
import { RedisClientService } from 'src/modules/shared/redis-utils/redis-client/redis-client.service';
import { AccountService } from '../../services/account/account.service';
import { AccountVo } from './vo/account.vo';
import { classToPlain, plainToClass } from 'class-transformer';
import { LoggerService } from 'src/modules/shared/services/loger/logger.service';
// @PermissionModule('账号模块')
@Controller('account')
export class AccountController {
  constructor(
    private readonly accountService: AccountService,
    private readonly redisClientService: RedisClientService,
    private readonly loggerService: LoggerService
  ) {}

  @Post()
  async createAccount(@Body() data: any) {
    return await this.accountService.createAccount(data);
  }

  @Get()
  async accountList(
    @Query('pageSize', new DefaultValuePipe(5), ParseIntPipe) pageSize: number
  ): Promise<AccountVo[]> {
    console.log(pageSize, '=====');
    this.loggerService.info('简单的打印');
    // this.redisClientService.redisClient.set('name', 'hello');
    const account = await this.accountService.accountList();
    return plainToClass(AccountVo, account);
    // return account;
    // throw new HttpException('服务器错误', HttpStatus.BAD_GATEWAY);
  }

  @Sse('sse')
  sse(): Observable<MessageEvent> {
    return interval(1000).pipe(map((_) => ({ data: { hello: 'world' } })));
  }
  /**
   * 客户端使用
   * 
  const eventSource = new EventSource('http://www.localhost:5000/account/sse');
  eventSource.onmessage = ({ data }) => {
    const message = document.createElement('li');
    message.innerText = 'New message: ' + data;
    document.body.appendChild(message);
  }
   */
}
